package com.bwt.top.bwt_ad_flutter.view.widget;

import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bwt.top.bwt_ad_flutter.ad.BwtBannerAd;
import com.bwt.top.bwt_ad_flutter.manager.BwtBannerAdManager;
import com.bwt.top.bwt_ad_flutter.model.AdParams;

import io.flutter.plugin.platform.PlatformView;

public class BwtBannerAdWidget  implements PlatformView {


    private FrameLayout adContainer;

    public BwtBannerAdWidget(@NonNull Context context, @NonNull AdParams adParams){
        BwtBannerAdManager bannerManager = BwtBannerAdManager.getInstance();
        BwtBannerAd ad = bannerManager.getBwtBannerAdMap().get(adParams.getAdId());
        this.adContainer = ad.getAdContainer();
        adContainer.setX(0);
        adContainer.setY(0);
        float density = context.getResources().getDisplayMetrics().density;
        Double adWidth = adParams.getAdWidth();
        Double adHeight = adParams.getAdHeight();
        int width = adWidth != null && adWidth > 0 ? (int) (density * adWidth) : ViewGroup.LayoutParams.MATCH_PARENT;
        int height = adHeight != null && adHeight > 0 ? (int) (density * adHeight) : ViewGroup.LayoutParams.WRAP_CONTENT;
        adContainer.setLayoutParams(new ViewGroup.LayoutParams(width, height));
    }

    @Nullable
    @Override
    public View getView() {
        return this.adContainer;
    }

    @Override
    public void dispose() {
         release();
    }


    public void release() {
        try {
            if (this.adContainer != null) {
                this.adContainer.removeAllViews();
                this.adContainer = null;
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}
